package com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.dao.impl;


import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.core.inface.PageFunction;
import com.audaque.springboot.foshanupload.core.model.qo.DynamicQo;
import com.audaque.springboot.foshanupload.core.model.qo.page.Page;
import com.audaque.springboot.foshanupload.db.util.page.PageUtil;
import com.audaque.springboot.foshanupload.pagehelper.component.MybatisPageHelperPageConvert;
import com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.dao.SysUserMpgtDao;
import com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.mapper.SysUserMpgtMapper;
import com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.model.kbo.SysUserMpgtKbo;
import com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.model.pojo.SysUserMpgtPojo;
import com.audaque.springboot.foshanupload.web.mbactdemo.mpgt.model.qo.SysUserMpgtQo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageRowBounds;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zgb
 * @since 2023-01-23
 */

@Slf4j
@Repository
public class SysUserMpgtDaoImpl implements SysUserMpgtDao {

    @Autowired
    private SysUserMpgtMapper sysUserMpgtMapper;


    @Resource
    private MybatisPageHelperPageConvert mybatisPageHelperPageConvert;


    @Override
    public String insert(SysUserMpgtPojo pojo, Boolean ignoreDuplicateExceptionYn) throws Exception {
        try {
            sysUserMpgtMapper.insert(pojo);
        } catch (Exception exception) {
            String s;
            Throwable cause = exception.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
                s = "Dao.insert:表中已存在主键,已设置允许忽略次此异常";
                log.debug(s);
                if (!ignoreDuplicateExceptionYn) {
                    throw new Exception(s);
                }
            } else {
                s = "Dao.insert:保存失败";
                log.error(s, exception);
                throw new Exception(s);
            }

        }

        Long id = pojo.getUserId();
        if (id == null) {
            return null;
        }
        return Long.toString(id);
    }

    @Override
    public void update(SysUserMpgtPojo pojo) throws Exception {
        if (pojo.getUserId() == null) {
            throw new Exception("ID不能为空");
        }
        sysUserMpgtMapper.update(pojo);
    }

    @Override
    public void delete(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new Exception("ID不能为空");
        }
        sysUserMpgtMapper.delete(id, UUID.randomUUID().toString());
    }


    @Override
    public Page<SysUserMpgtPojo> queryAndCount(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();

        List<Object> queryAndCount = sysUserMpgtMapper.queryAndCount(sysUserMpgtKbo, sysUserMpgtQo);

        List<SysUserMpgtPojo> list = (List<SysUserMpgtPojo>) queryAndCount.get(0);

        int count = ((List<Integer>) queryAndCount.get(1)).get(0);//总数


        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<SysUserMpgtPojo> queryThenCount(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();

        return PageUtil.execute(page, new PageFunction<SysUserMpgtPojo>() {

            @Override
            public int count() {
                sysUserMpgtQo.clearlLimitQo();
                sysUserMpgtQo.setCountWhat();
                List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo);
                Long count = (Long) list.get(0).get("total");
                ;
                return count.intValue();
            }

            @Override
            public List<SysUserMpgtPojo> query() {
                sysUserMpgtQo.clearCountWhat();
                //mybatis原生内存分页：不含total,RowBounds不能为null，否则报空
                RowBounds rowBound = new RowBounds(page.getOffset(), page.getLimit());
                List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo, rowBound);
                List<SysUserMpgtPojo> collect = list.stream().map(e -> BeanUtil.mapToBean(e, SysUserMpgtPojo.class, false)).collect(Collectors.toList());
                return collect;
            }

        });
    }

    @Override
    public Page<SysUserMpgtPojo> queryThenCountHelper(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();
        sysUserMpgtQo.clearlLimitQo();
        sysUserMpgtQo.clearCountWhat();
        //传参方式： PageHelper.startPage，PageRowBounds，@Param("pageNumKey") int pageNum,@Param("pageSizeKey") int pageSize
        //total获取方式： com.github.pagehelper.Page，om.github.pagehelper.PageInfo，om.github.pagehelper.PageRowBounds
        //紧跟在这个方法后的第一个MyBatis 查询方法会被进行分页。
        com.github.pagehelper.Page<SysUserMpgtPojo> pager = PageHelper.startPage(page.getPage(), page.getRows());
        //com.github.pagehelper.Page<SysUserMpgtPojo> pager1 = PageHelper.offsetPage(page.getOffset(), page.getLimit());
        List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo);
        log.debug("list:" + list);
        //PageInfo pageInfo = new PageInfo(list);
        List<SysUserMpgtPojo> result = pager.getResult();
        log.debug("result:" + result);
        PageInfo<SysUserMpgtPojo> pageInfo = pager.toPageInfo();
        log.debug("pageInfo:" + pageInfo);
        page = mybatisPageHelperPageConvert.pager2Page(pageInfo);

        List<SysUserMpgtPojo> collect = list.stream().map(e -> BeanUtil.mapToBean(e, SysUserMpgtPojo.class, false)).collect(Collectors.toList());
        log.debug("collect:" + collect);
        page.setRecords(collect);

        return page;


    }

    @Override
    public Page<SysUserMpgtPojo> queryThenCountHelper2(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();
        sysUserMpgtQo.clearlLimitQo();
        sysUserMpgtQo.clearCountWhat();
        //传参方式： PageHelper.startPage，PageRowBounds，@Param("pageNumKey") int pageNum,@Param("pageSizeKey") int pageSize
        //total获取方式： com.github.pagehelper.Page，om.github.pagehelper.PageInfo，om.github.pagehelper.PageRowBounds
        PageRowBounds pageRowBounds = new PageRowBounds(page.getPage(), page.getRows());
        List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo, pageRowBounds);
        log.debug("list:" + list);
        List<SysUserMpgtPojo> collect = list.stream().map(e -> BeanUtil.mapToBean(e, SysUserMpgtPojo.class, false)).collect(Collectors.toList());
        log.debug("collect:" + collect);
        page.setRecords(collect);
        page.setTotal(pageRowBounds.getTotal().intValue());

        return page;


    }


    @Override
    public Page<SysUserMpgtPojo> queryThenCountHelper3(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        Page<SysUserMpgtPojo> page = sysUserMpgtQo.toPage();
        sysUserMpgtQo.clearlLimitQo();
        sysUserMpgtQo.clearCountWhat();
        //传参方式： PageHelper.startPage，PageRowBounds，@Param("pageNumKey") int pageNum,@Param("pageSizeKey") int pageSize
        //total获取方式： com.github.pagehelper.Page，om.github.pagehelper.PageInfo，om.github.pagehelper.PageRowBounds
        List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo, page.getPage(), page.getRows());
        log.debug("list:" + list);
        com.github.pagehelper.Page<SysUserMpgtPojo> pager = (com.github.pagehelper.Page) list;
        List<SysUserMpgtPojo> collect = list.stream().map(e -> BeanUtil.mapToBean(e, SysUserMpgtPojo.class, false)).collect(Collectors.toList());
        log.debug("collect:" + collect);
        page.setRecords(collect);
        page.setTotal(new Long(pager.getTotal()).intValue());

        return page;


    }


    @Override
    public List<SysUserMpgtPojo> queryList(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        RowBounds rowBound = new RowBounds();
        List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo);
        List<SysUserMpgtPojo> collect = list.stream().map(e -> BeanUtil.mapToBean(e, SysUserMpgtPojo.class, false)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public SysUserMpgtPojo queryItem(SysUserMpgtKbo sysUserMpgtKbo, SysUserMpgtQo sysUserMpgtQo) {
        List<Map> list = sysUserMpgtMapper.queryOrCount(sysUserMpgtKbo, sysUserMpgtQo);
        SysUserMpgtPojo item = BeanUtil.mapToBean(list.get(0), SysUserMpgtPojo.class, false);
        return item;
    }

    @Override
    public SysUserMpgtPojo queryItem(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new Exception("ID不能为空");
        }
        SysUserMpgtQo sysUserMpgtQo = new SysUserMpgtQo();
        sysUserMpgtQo.setUserId(Long.parseLong(id));
        List<Map> list = sysUserMpgtMapper.queryOrCount(null, sysUserMpgtQo);
        SysUserMpgtPojo item = BeanUtil.mapToBean(list.get(0), SysUserMpgtPojo.class, false);
        return item;
    }

    @Override
    public Integer count(SysUserMpgtQo sysUserMpgtQo) {
        DynamicQo dynamicQo = sysUserMpgtQo.getDynamicQo();
        if (dynamicQo != null) {
            dynamicQo.setCountWhat("*");
        } else {
            dynamicQo = new DynamicQo();
            dynamicQo.setCountWhat("*");
            sysUserMpgtQo.setDynamicQo(dynamicQo);
        }
        sysUserMpgtQo.setLimitQo(null);
        List<Map> list = sysUserMpgtMapper.queryOrCount(null, sysUserMpgtQo);
        Long count = (Long) list.get(0).get("total");
        ;
        return count.intValue();
    }


}
